package communication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import client.Client;
import client.communication.listeners.AuthenticationListener;
import client.communication.listeners.InsertDataListener;
import client.communication.listeners.PingListener;

import message.Message;

public class ClientCommunicator extends Communicator
{
	private PrintWriter out;
	private BufferedReader in;
	private Socket socket;
	
	public ClientCommunicator(Socket socket, Client client) throws InstantiationException
	{
		try
		{
			this.socket = socket;
			this.out = new PrintWriter(socket.getOutputStream(), true);
			this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));			
		}
		catch (IOException e)
		{
			throw new InstantiationException();
		}
		
		this.addListener(new PingListener(client));
		this.addListener(new AuthenticationListener(client));
		this.addListener(new InsertDataListener(client));
	}
	
	public void sendMessage(Message message)
	{
		out.println(messageFactory.serializeMessage(message));
	}
	
	@Override
	public void run()
	{
		while (true)
		{
			Message message = null;
			
			try
			{
				message = super.messageFactory.unserializeMessage(in.readLine());
			}
			catch (IOException e) {}
			
			if (message != null)
				delegateMessageEvent(new MessageReceivedEvent(message));
		}
	}
}
